﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.Diagnostics;
using System.Windows.Forms;
using Contract;
using System.IO;
using System.Net;
using System.Net.Sockets;


namespace client
{
    [ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Reentrant)]
    public partial class Form1 : Form
    {
        string PCN;
        IDataUploader Proxy;

        public Form1(string pcn)
        {



            InitializeComponent();

            this.Proxy = createProxy();

            MyFile[] mfs = Proxy.GetfilesList(null);
            RefreshFileList(mfs);
            CreatHost();
            this.PCN = pcn;
            CallBack.handler = RefreshFileList;


        }

        public void CreatHost()
        {
            // create a hosting process for Service
            ServiceHost host = new ServiceHost(typeof(CallBack));
            NetTcpBinding binding = new NetTcpBinding();
            binding.TransferMode = TransferMode.Buffered;
            binding.ReceiveTimeout = TimeSpan.MaxValue;
            binding.MaxReceivedMessageSize = int.MaxValue;
            host.AddServiceEndpoint(typeof(ICallBack), binding,
            new Uri("net.tcp://" + Dns.GetHostAddresses(Environment.MachineName)[3].ToString() + ":8001/CallBack"));
            host.Open();
            /////////////
        }

        public void RunCallback(string pcn)
        {
            
        }

        public IDataUploader createProxy()
        {
            //////////////////////////////////////
            NetTcpBinding binding = new NetTcpBinding();
            binding.TransferMode = TransferMode.Streamed;
            binding.SendTimeout = TimeSpan.MaxValue;
            binding.MaxReceivedMessageSize = 9223372036854775807;

            EndpointAddress address = new EndpointAddress("net.tcp://" + Dns.GetHostAddresses(Environment.MachineName)[3] + ":5000/DataUploader");

            ChannelFactory<IDataUploader> channel = new ChannelFactory<IDataUploader>(binding, address);
            IDataUploader Proxy = channel.CreateChannel();
            return Proxy;
            ///////////////////////////////////////////////
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            linkLabel1.Text = PCN;
            tabPage1.Text = @"Private";
            tabPage2.Text = @"Group";

        }

        private void listView1_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                var loc = listView1.HitTest(e.Location);
                if (loc.Item != null)
                {
                    contextMenuStrip1.Show(listView1, e.Location);
                }
            }
        }

        private void btnUpload_Click(object sender, EventArgs e)
        {

            Proxy = createProxy();


            OpenFileDialog dialog = new OpenFileDialog();
            dialog.ShowDialog();
            string filename = Path.GetFileName(dialog.FileName);
            Stream uploadStream = new FileStream(dialog.FileName, FileMode.Open);
            MyFile m = new MyFile() { Value = uploadStream, Name = filename, Size = uploadStream.Length, PCN = this.PCN };
            try
            {
                Proxy.Upload(m);
            }
            catch
            { 
                MessageBox.Show("exception"); 
            }
            //  ((IClientChannel)Proxy).Close();
            // RefreshFileList();

        }

        public void RefreshFileList(MyFile[] files)
        {
            MyFile[] mfs = files;

       //     mfs = Proxy.Getfilesinfo(null);

            listView1.Items.Clear();

            foreach (var file in mfs)
            {
                ListViewItem item = new ListViewItem();

                
                item.SubItems.Add( Convert.ToString(file.Size));
                item.SubItems[1].Text = Convert.ToString(file.Size);


                 item.SubItems.Add( Convert.ToString(file.Name));
            item.SubItems.Add( Convert.ToString(file.Name));

                listView1.Items.Add(item);
            }
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Form2 f2 = new Form2();
            f2.Show();
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count == 0)
            {
                MessageBox.Show("No File is Selected");
            }
            else
            {
                ListViewItem item = listView1.SelectedItems[0];

                string path = item.SubItems[0].Text;

                SaveFileDialog dialog = new SaveFileDialog()
                {
                    FileName = Path.GetFileName(path)
                };

                dialog.ShowDialog(this);
                if (dialog.FileName != "")
                {
                    using (FileStream output = new FileStream(dialog.FileName, FileMode.Create))
                    {
                        Stream downloadStream = Proxy.Download(path);
                        byte[] bt = ReadBytestoStream(downloadStream);
                        output.Write(bt, 0, bt.Length);
                        MessageBox.Show("file is downloaded completly!");
                    }

                    Process.Start(dialog.FileName);
                }
                //     ((IClientChannel)Proxy).Close();

            }
        }

        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count == 0)
            {
                MessageBox.Show("No File is Selected");
            }
            else
            {
                ListViewItem item = listView1.SelectedItems[0];

                string path = item.SubItems[0].Text;

                Proxy.Delete(path);
                MyFile[] mfs = Proxy.GetfilesList(null);
                RefreshFileList(mfs);
            }

        }

        public static byte[] ReadBytestoStream(Stream input)
        {
            byte[] buffer = new byte[16 * 1024];
            using (MemoryStream ms = new MemoryStream())
            {
                int read;
                while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }
                return ms.ToArray();
            }
        }


      


    }


}

